<template>
	<view>
		<view class="content">
	 <!-- #ifdef MP-WEIXIN || MP-ALIPAY  -->
      <u-navbar
          title="订单详情"
          <!-- #ifdef MP-WEIXIN -->
          leftIconSize="40rpx"
          <!-- #endif -->
          <!-- #ifdef MP-ALIPAY -->
          leftIconSize="0rpx"
          <!-- #endif -->
          :safeAreaInsetTop="true"
          :placeholder="true"
          :autoBack="true"
          bgColor="#F7F8F7"
      >
      </u-navbar>
	  <!-- #endif -->
			<view class="price-card">
				<view class="price">
					<text class="price-symbol">￥</text>
					{{order.totalAmount ? order.totalAmount.toFixed(2) : 0}}
				</view>
				<view class="desc">
					<text v-if="order.mchType == 3">
						（现金支付）
					</text>
					订单金额
				</view>
				<view class="status-badge" v-if="order.id">
					<view v-if="order.status == 0" class="color-primary">待支付</view>
					<view v-else-if="order.status == 1" class="color-primary">待使用</view>
					<view v-else-if="order.status == 2">已完成</view>
					<view v-else-if="order.status == 3">退单</view>
					<view v-else-if="order.status == 4" class="top-tag color-primary">拼团中</view>
					<view v-else-if="order.status == 5">拼团失败</view>
					<view v-else-if="order.status == 8">退款中</view>
				</view>
			</view>
			<view class="code-card" v-if="order.verifyCode && ( order.type == 1 || order.type == 2 || order.type == 5)">
				<view class="title-view"> 
					<view class="icon">
<!--						<u-image :src="`/static/image/order/view-order-detail-blue.png`" width="34rpx" height="34rpx" mode="aspectFit"></u-image>-->
							<u-image :src="`${staticFileUrl}/image/order/view-order-detail-blue.png`" width="34rpx" height="34rpx" mode="aspectFit"></u-image>
					</view>
					<view class="title">
						使用凭证
					</view>
				</view>
				<view class="qr-code" :class="order.status == 2 ? 'qr-code-use' : ''">
					<u-image :src="verifyCodeQr" width="234rpx" height="234rpx" mode="aspectFit"></u-image>
				</view>
				<view class="code-line" :style="!order.inDate ? 'margin-bottom:0;' : ''">
					<view class="line-title">
						核销券号：
					</view>
					<view class="line-value" @click="copyCode(order.verifyCode)" @longpress="copyCode(order.verifyCode)">
						{{order.verifyCode}}
					</view>
				</view>
				<view class="code-line" style="margin-bottom:0;" v-if="order.inDate">
					<view class="line-title">
						到期时间：
					</view>
					<view class="line-value">
						{{order.inDate | formatDate}} 后到期
					</view>
				</view>
				
				<!-- 已使用徽标 -->
				<view class="code-badge" v-if="order.status == 2">
					<!-- 外圈 -->
					<view class="outer-ring">
						<!-- 内圈 -->
						<view class="inner-ring">
							<!-- 中间标签 -->
							<view class="tag">
								已使用
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="detail-card">
				<view class="detail-line">
					<view class="line-title">
						订单时间：
					</view>
					<view class="line-value">
						{{order.gmtPayment | formatDate}}
					</view>
				</view>
				<view class="detail-line">
					<view class="line-title">
						订单编号：
					</view>
					<view class="line-value" @click="copyCode(order.outTradeNo)" @longpress="copyCode(order.outTradeNo)">
						{{order.outTradeNo ? order.outTradeNo : '--'}}
					</view>
				</view>
				<view class="detail-line">
					<view class="line-title">
						支付单号：
					</view>
					<view class="line-value" @click="copyCode(order.payChannelOrderNo)" @longpress="copyCode(order.payChannelOrderNo)">
						{{order.payChannelOrderNo ? order.payChannelOrderNo : '--'}}
					</view>
				</view>
				<view class="detail-line">
					<view class="line-title">
						购买会员：
					</view>
					<view class="line-value" v-if="order.mobile">
						{{order.mobile | formatPhoneNum}}
					</view>
				</view>
				<view class="detail-line">
					<view class="line-title"> 
						售卖门店：
					</view>
					<view class="line-value">
						{{order.storeName ? order.storeName : '--'}}
						<text v-if="order.deviceNo">
							（{{order.deviceNo}}-{{order.deviceTypeName}}）
						</text>
					</view>
				</view>
				<view class="detail-line">
					<view class="line-title">
						订单状态：
					</view>
					<view class="line-value">
						<view v-if="order.status == 0">待支付</view>
						<view v-else-if="order.status == 1">待使用</view>
						<view v-else-if="order.status == 2">已完成</view>
						<view v-else-if="order.status == 3">退单</view>
						<view v-else-if="order.status == 4">拼团中</view>
						<view v-else-if="order.status == 5">拼团失败</view>
						<view v-else-if="order.status == 8">退款中</view>
						
					</view>
				</view>
				<view class="btn-list" v-if="(order.activityTypeId == activityTypeEnum.SECKILL || 
							order.activityTypeId == activityTypeEnum.GROUP_BOOKING) && 
							(order.status == activityOrderStateEnum.CREATE || order.status == activityOrderStateEnum.PAY_SUCCESS_AND_TO_BE_USED
							 || order.status == activityOrderStateEnum.GROUPON|| order.status == activityOrderStateEnum.GROUPON_FAIL) && 
							(order.payStatus == activityOrderPayStateEnum.SUCCESS || order.payStatus == activityOrderPayStateEnum.REFUND_FAIL)">
					<view class="btn-refund">
						<u-button :plain="true" type="error" text="申请退款" shape="circle" :disabled="isRefund" @click="applyRefund"></u-button>
					</view>
				</view>
			</view>
			<view class="goods-list" v-if="order.commodityList && order.commodityList.length > 0">
				<view class="goods-card" v-for="(goods,index) in order.commodityList" :key="index">
					<view class="goods-img">
						<u-image :src="goods.fileName?imageUrl+goods.fileName:defaultProductImage" width="90rpx" height="90rpx"></u-image>
					</view>
					<view class="goods-right">
						<view class="goods-detail">
							<view class="goods-name">
								{{goods.name ? goods.name : '--'}}
							</view>
							<view class="goods-other">
								<view class="goods-other-one">
									单价：￥{{goods.price ? goods.price.toFixed(2) : 0}}
								</view>
								<view class="goods-other-one">
									数量：{{goods.num ? goods.num : 0}}
								</view>
							</view>
						</view>
						<view class="goods-price">
							<text class="price-symbol">￥</text>
							{{(goods.price * goods.num) ? (goods.price * goods.num).toFixed(2) : 0}}
						</view>
					</view>
				</view>
			</view>
			<view class="goods-list" v-else>
				<view class="goods-card">
					<view class="goods-img">
						<u-image :src="defaultProductImage" width="90rpx" height="90rpx"></u-image>
					</view>
					<view class="goods-right">
						<view class="goods-detail">
							<view class="goods-name">
								<view v-if="order.type != 7">
									{{order.title ? order.title : '--'}}
								</view>
								<view>
									<text v-if="order.type == 4">储值套餐 {{Number(order.rechargeCoin) + Number(order.donateCoin)}} 个游戏币</text>
									<text v-else-if="order.type == 0 || order.type == 7">
										<text v-if="deviceTypeEnum.MARSHMALLOW != order.deviceTypeId">游戏币（个）</text>
									</text>
								</view>
							</view>
							<view class="goods-other">
								<view class="goods-other-one">
									数量：{{order.quantity ? order.quantity : '--'}}
								</view>
							</view>
						</view>
						<view class="goods-price">
							<text class="price-symbol">￥</text>
							{{order.price ? order.price.toFixed(2) : 0}}
						</view>
					</view>
				</view>
			</view>
		</view>
    <u-tabbar v-if="order.payStatus === 1 && isBluetooth"  :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" :border="false">
      <view class="buttonBox">
        <u-button class="buttonBox-button"  @click="reShipment" type="primary" shape="circle" text="重新出货"></u-button>
      </view>
    </u-tabbar>
	</view>
</template>

<script>
  import { eventBus } from '@/main.js'
	export default {
		data() {
			return {
				// 核销二维码
				verifyCodeQr: '',
				// 订单信息
				order: {},
				// 系统订单号
				outTradeNo: '',
				// 
				type: '',
				
				deviceTypeEnum: this.$deviceTypeEnum,
				// 默认图片
				defaultProductImage: this.$configPath.staticFileUrl + '/image/exchange/defaultProductImage.png',
				imageUrl: this.$configPath.imageUrl,
				staticFileUrl: this.$configPath.staticFileUrl,
				
				interval: null,
				
				activityTypeEnum: this.$activityTypeEnum,
				activityOrderStateEnum: this.$activityOrderStateEnum,
				activityOrderPayStateEnum: this.$activityOrderPayStateEnum,
				
				// 是否在退款中
				isRefund: false,
        //设备号
        deviceNo:null,
        //订单支付状态
        payStatus:null,
        //是否为蓝牙
        isBluetooth:false,
        //蓝牙连接状态
        connectionStatus:3,
			}
		},
    created() {
      // 监听事件
      eventBus.$on('connectionStatus', this.handleEventConnectionStatus)
    },
		onLoad(params) {
			this.outTradeNo = params.outTradeNo;
      this.isBluetooth = params.isBluetooth;
      this.deviceNo = params.deviceNo;
      this.payStatus = params.payStatus;
			this.type = params.type;
			this.getOrderDetailInfo();
			this.interval = setInterval(this.getOrderDetailInfo,5000);
		},
		onUnload() {
			console.log("销毁定时任务")
			if(this.interval){
				clearInterval(this.interval)
			}
		},
		methods: {
      handleEventConnectionStatus(connectionStatus) {
        console.log('connectionStatus变化',connectionStatus)
        this.connectionStatus = connectionStatus;
      },
      //蓝牙重新出货
      reShipment(){
        if (this.connectionStatus === 1){
          this.$helpers.toast("蓝牙正在连接中...");
          return;
        }
        if (this.connectionStatus === 3){
            this.$bluetooth.startBLEConnectionStateListening(this.deviceNo);//监听
            this.establishConnection(this.deviceNo);
            return;
        }
        this.$api("device.bluetoothReShipment",{'deviceNo':this.deviceNo,'outTradeNo':this.outTradeNo,'deviceId':this.order.deviceId}).then(res=>{
          if (res.status == 0) {
            this.$helpers.toast("重新出货成功");
          }else{
            getApp().err(res.msg);
          }
        })
      },
      //蓝牙建立连接
      establishConnection(deviceNo){
        //建立连接前先关掉蓝牙连接
        this.$bluetooth.closeBluetoothAdapter();
        setTimeout(() => {
          this.$bluetooth.initBluetooth(deviceNo,true);//连接
        }, 1000)
      },
			// 获取订单信息
			getOrderDetailInfo() {
				this.$api('member.findMemberOrderOne', {
					outTradeNo: this.outTradeNo,
					type: this.type
				}).then(res => {
					if (res.status == 0) {
						res.data.price = Number(res.data.price);
						res.data.num = Number(res.data.num);
						this.order = res.data;
						console.log("this.order", this.order)
						
						if (this.order.verifyCode && (this.order.type == 1 || this.order.type == 2 || this.order.type == 5)){
							this.verifyCodeQr = this.$mWxQrCode.createQrCodeImg(this.order.verifyCode, {
								size: parseInt(300) //二维码大小
							})
						}
					} else {
						this.$helpers.toast('请求数据失败:' + res.msg);
					}
				})
			},
			copyCode(value) {
				if(!value){
					return;
				}
				uni.setClipboardData({
					data: value,
					success: () => {
						this.$helpers.toast('复制成功');
					}
				});
			},
			
			// 申请退款
			applyRefund(){
				if(this.order.payStatus == 7){
					this.$helpers.toast("订单已完成退款，请勿重复操作")
					return;
				}
				if(this.order.payStatus == 8){
					this.$helpers.toast("订单正在退款中，请耐心等待退款结果")
					return;
				}
				if((this.order.activityTypeId != this.activityTypeEnum.SECKILL && this.order.activityTypeId != this.activityTypeEnum.GROUP_BOOKING) || 
					(this.order.status != this.activityOrderStateEnum.CREATE && this.order.status != this.activityOrderStateEnum.PAY_SUCCESS_AND_TO_BE_USED
						&& this.order.status != this.activityOrderStateEnum.GROUPON && this.order.status != this.activityOrderStateEnum.GROUPON_FAIL) || 
					(this.order.payStatus != this.activityOrderPayStateEnum.SUCCESS && this.order.payStatus != this.activityOrderPayStateEnum.REFUND_FAIL)){
					this.$helpers.toast("当前订单不支持退款")
					return;
				}
				uni.showModal({
					title: '温馨提示',
					content: '确定要申请退款吗',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							if(this.isRefund){
								return;
							}
							this.isRefund = true;
							uni.showLoading({
								title:"正在申请退款",
								mask: true
							})
							let params = {
								activityOrderId: this.order.id
							}
							this.$api("activity.applyRefund",params).then(res => {
								if(res.status == 0){ 
									this.getOrderDetailInfo();
									setTimeout(() => {
										uni.hideLoading();
										this.isRefund = false;
										this.$helpers.toast("申请退款成功");
									},1000)
								}else{
									uni.hideLoading();
									this.isRefund = false;
									this.$helpers.toast(res.msg);
								}
							}).catch(e => {
								uni.hideLoading();
								this.isRefund = false;
								this.$helpers.toast("申请失败，服务器访问失败");
								console.log(e);
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
  .buttonBox{
    padding: 0 200rpx;
    width: 100%;
    display: flex;
    justify-content: center;
  }
  /deep/ .u-tabbar__content{
    background-color: #F7F8F7 !important;
  }
  /deep/ .u-button--primary{
    border-color:#8F8EF8 !important;
    background-color:#8F8EF8 !important;
  }
	.content{
		padding: 24rpx;
		.price-card{
			padding: 32rpx;
			margin-bottom: 20rpx;
			background: linear-gradient(90.00deg, rgb(126, 125, 243),rgb(150, 149, 250) 99.519%);
			border-radius: 20rpx;
			overflow: hidden;
			position: relative;
			
			.price{
				text-align: center;
				color: white;
				font-size: 48rpx;
				font-weight: 400;
				.price-symbol{
					margin-right: 5rpx;
				}
			}
			.desc{
				text-align: center;
				color: rgba(255, 255, 255, 0.6);
				font-size: 28rpx;
				font-weight: 400;
				margin-top: 8rpx;
			}
			
			.status-badge{
				position: absolute;
				top: 15rpx;
				right: -50rpx;
				transform: rotate(32.65deg);
				width: 200rpx;
				background-color: white;
				padding: 10rpx;
				text-align: center;
				font-size: 22rpx;
				.color-primary {
					color: rgb(234, 97, 0) !important;
				}
				.color-purple{
					color: #7E7DF3 !important;
				}
			}
		}
		
		.detail-card,.code-card{
			background-color: white;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			font-size: 28rpx;
			.code-line,.detail-line{
				display: flex;
				margin-bottom: 30rpx;
				.line-title{
					width: 160rpx;
				}
				.line-value{
					flex: 1;
					// text-align: right;
					color: rgba(0, 0, 0, 0.6);
					// 强制换行
					word-wrap:break-word;
					// 强制英文单词换行
					word-break:break-word;
					overflow: hidden;
					-webkit-line-clamp: 2;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
				}
			}
			
			.btn-list{
				display: flex;
				justify-content: flex-end;
				.btn-refund{
					width: 200rpx;
				}
			}
		}
		.code-card{
			position: relative;
			.title-view{
				display: flex;
				align-items: center;
				.icon{
					margin-right: 12rpx;
				}
				.title{
					font-size: 32rpx;
					font-weight: 400;
				}
			}
			
			.qr-code{
				padding: 50rpx;
				display: flex;
				justify-content: center;
			}
			.qr-code-use{
				opacity: 0.1;
			}
			.code-badge{
				position: absolute;
				right: 50rpx;
				top: 50rpx;
				
				.outer-ring{
					width: 86rpx;
					height: 86rpx;
					border: 2px solid rgba(126, 125, 243, 0.4);
					background-color: white;
					border-radius: 50%;
					
					display: flex;
					align-items: center;
					justify-content: center;
					.inner-ring{
						width: 66rpx;
						height: 66rpx;
						border: 1px solid rgba(126, 125, 243, 0.4);
						background-color: white;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						.tag{
							position: absolute;
							background: rgb(255, 255, 255);
							border: 1px solid rgba(126, 125, 243, 0.4);
							
							border-radius: 4rpx;
							width: 103rpx;
							padding: 3rpx;
							
							color: rgba(126, 125, 243, 0.4);
							text-align: center;
							font-size: 23rpx;
							
							transform: rotate(-32.65deg);
						}
					}
				}
			}
		}
		
		.detail-card{
			.detail-line{
				.line-value{
					text-align: right;
				}
			}
			.detail-line:last-child{
				margin-bottom: 0 !important;
			}
		}
		
		.goods-list{
			font-size: 28rpx;
			.goods-card{
				display: flex;
				align-items: center;
				background-color: white;
				border-radius: 20rpx;
				padding: 30rpx;
				margin-bottom: 20rpx;
				.goods-img{
					
				}
				.goods-right{
					flex: 1;
					margin-left: 30rpx;
					display: flex;
					align-items: flex-end;
					justify-content: space-between;
					.goods-detail{
						flex: 1;
						.goods-name{
							// 强制换行
							word-wrap:break-word;
							// 强制英文单词换行
							word-break:break-word;
							overflow: hidden;
							-webkit-line-clamp: 2;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-box-orient: vertical;
						}
						.goods-other{
							color: rgba(0, 0, 0, 0.6);
							font-size: 24rpx;
							margin-top: 22rpx;
							display: flex;
							align-items: center;
							.goods-other-one{
								margin-right: 53rpx;
							}
						}
					}
					.goods-price{
						margin-left: 30rpx;
						font-size: 30rpx;
						font-weight: 400;
						
						.price-symbol{
							margin-right: 10rpx;
						}
					}
				}
			}
		}
		
	}
</style>
